package com.pc_project.service.impl;

import com.pc_project.domain.Audit;
import com.pc_project.domain.authenticate.AuditAuthenticator;
import com.pc_project.domain.User;
import com.pc_project.domain.authenticate.UserAuthenticator;
import com.pc_project.mapper.AuditDao;
import com.pc_project.mapper.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private AuditDao auditDao;

    @Autowired
    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//        根据传进来的用户名进行查询是否有用户
//        这里有一个bug，就是不知道传进来的用户是审核者还是普通类型用户。
//        如果查两次就会产生同名对象的bug，那么只能够对审核者作特殊处理，审核者只能有那么一个账号，是那个账号就进审核者判断，否则一律进入普通用户

        if (username.equals("admin")) {
            Audit audit = null;
            audit = auditDao.selectOneByAUsernameAudit(username);
//        通过object帮助类查询，是否有用户，没有用户就抛异常
            if (Objects.isNull(audit)) {
                throw new RuntimeException("没有该用户");
            }

            return new AuditAuthenticator(audit);
        }

//        todo:如果不是admin对象那么我们直接查询普通用户。
        User user=userDao.selectOneByUsername(username);
        if(Objects.isNull(user)){
            throw new RuntimeException("没有该用户");
        }

        return new UserAuthenticator(user);
    }
}
